package com.tulele.vtool.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.green.model.v20180509.TextScanRequest;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.tulele.vtool.config.AliyunGreenConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.*;

@Slf4j
@Component
public class AliyunGreenClientUtil {

    @Autowired
    private AliyunGreenConfig aliyunGreenConfig;

    public static AliyunGreenClientUtil aliyunGreenClientUtil;

    @PostConstruct
    public void init() {
        aliyunGreenClientUtil = this;
    }

    /**
     * 获取GreenClient实例
     * @return
     */
    private static IAcsClient getGreenClient(){
        IClientProfile profile = DefaultProfile.getProfile(aliyunGreenClientUtil.aliyunGreenConfig.getRegionId(), aliyunGreenClientUtil.aliyunGreenConfig.getAccessKeyId(), aliyunGreenClientUtil.aliyunGreenConfig.getAccessKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);

        return client;
    }

    /**
     * 文本扫描结果
     * @param text
     * @return
     * @throws Exception
     */
    public static String textScan(String text) throws Exception {

        String scanResult = "normal";

        TextScanRequest textScanRequest = new TextScanRequest();
        textScanRequest.setSysAcceptFormat(FormatType.JSON); // 指定api返回格式
        textScanRequest.setHttpContentType(FormatType.JSON);
        textScanRequest.setSysMethod(com.aliyuncs.http.MethodType.POST); // 指定请求方法
        textScanRequest.setSysEncoding("UTF-8");
        textScanRequest.setSysRegionId(aliyunGreenClientUtil.aliyunGreenConfig.getRegionId());
        List<Map<String, Object>> tasks = new ArrayList<Map<String, Object>>();
        Map<String, Object> task1 = new LinkedHashMap<String, Object>();
        task1.put("dataId", UUID.randomUUID().toString());
        /**
         * 待检测的文本，长度不超过10000个字符
         */
        task1.put("content", text);
        tasks.add(task1);
        JSONObject data = new JSONObject();

        /**
         * 检测场景，文本垃圾检测传递：antispam
         **/
        data.put("scenes", Arrays.asList("antispam"));
        data.put("tasks", tasks);
        textScanRequest.setHttpContent(data.toJSONString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);
        // 请务必设置超时时间
        textScanRequest.setSysConnectTimeout(3000);
        textScanRequest.setSysReadTimeout(6000);
        try {
            HttpResponse httpResponse = getGreenClient().doAction(textScanRequest);
            if(httpResponse.isSuccess()){
                JSONObject scrResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
                if (200 == scrResponse.getInteger("code")) {
                    JSONArray taskResults = scrResponse.getJSONArray("data");
                    for (Object taskResult : taskResults) {
                        if(200 == ((JSONObject)taskResult).getInteger("code")) {

                            JSONArray sceneResults = ((JSONObject)taskResult).getJSONArray("results");
                            for (Object sceneResult : sceneResults) {

                                scanResult = ((JSONObject)sceneResult).getString("label");

                            }

                        } else {
                            log.info("task process fail:" + ((JSONObject)taskResult).getInteger("code"));
                        }
                    }
                } else {
                    log.info("detect not success. code:" + scrResponse.getInteger("code"));
                }
            }else{
                log.info("response not success. status:" + httpResponse.getStatus());
            }
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return scanResult;
    }


}
